<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="出库单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipmentCode">
              <a-input v-model="model.shipmentCode" placeholder="请输入出库单号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
              <tsl-erp-customer v-model="model.customerName"   :disabled="formDisabled"> </tsl-erp-customer>
              <!--              <j-dict-select-tag type="list"  dictCode="erp_customer,name,id" placeholder="请选择客户" />-->
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="收货地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="address">
              <a-input v-model="model.address" placeholder="请输入收货地址" :disabled="formDisabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowFlag">
              <j-dict-select-tag type="list" v-model="model.flowFlag" :disabled="formDisabled" dictCode="shipment_flow_type" placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="单价类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="priceType">
              <j-dict-select-tag type="list" v-model="model.priceType" @change="handlePriceType" :disabled="formDisabled" dictCode="unit_price_type" placeholder="请选择单价类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="currency">
              <j-dict-select-tag type="list" v-model="model.moneyUnit" :disabled="formDisabled" dictCode="money_unit" placeholder="请选择币种" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="发货人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="drawer">
<!--              <j-select-user-by-dep v-model="model.drawer" :disabled="formDisabled" :multi="false" />-->
              <a-input v-model="model.drawer" :disabled="formDisabled"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="发货日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="shipmentDate">
              <j-date placeholder="请选择发货日期" v-model="model.shipmentDate" :disabled="formDisabled" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="其他金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherAmounts">
              <a-input-number v-model="model.otherAmounts" placeholder="请输入其他金额" :disabled="formDisabled" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="客户订单费用" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderFees">
              <a-input-number v-model="model.orderFees" placeholder="请输入客户订单费用" :disabled="formDisabled" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="总金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalAmount">
              <a-input-number v-model="model.totalAmount" default-value="0" placeholder="请输入总金额"  disabled style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="总吨数" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="totalTonnage">
              <a-input-number v-model="model.totalTonnage" default-value="0" placeholder="请输入总吨数" disabled style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" >
            <a-tabs v-model="activeKey" @change="handleChangeTabs">
              <a-tab-pane tab="发货信息" :key="refKeys[0]" :forceRender="true">
                <a-row :gutter="24" style="margin-bottom: 10px;">
                  <a-col :span="24">
                    <a-button @click="addShipping" icon="plus">新增</a-button>
                    <a-button type="danger"  icon="delete" @click="onDel">删除</a-button>
                  </a-col>
                </a-row>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="crmShipmentGoodsShippingTable.loading"
                  :columns="crmShipmentGoodsShippingTable.columns"
                  :dataSource="crmShipmentGoodsShippingTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar-config="{ btn: [] }"
                  :toolbar="!formDisabled"
                >
                  <template #toolbarPrefix>  <!-- 覆盖整个工具栏 -->
<!--                    <a-space>
                      &lt;!&ndash;a-button type="primary" icon="plus" @click="onAddRow">新增</a-button>&ndash;&gt;
                      <a-button type="danger"  icon="delete" @click="onDel">删除</a-button>
                    </a-space>-->
                  </template>
                  <template v-slot:thisQuantity="{ row }">
                    <a-input-number :disabled="formDisabled" style="width:100%" v-model="row.thisQuantity" @change="thisQuantityInput(row)" :default-value="0" />
                  </template>
                  <template v-slot:unitPrice="{ row }">
                    <a-input-number :disabled="formDisabled" style="width:100%" v-model="row.unitPrice" @change="thisQuantityInput(row)" :default-value="0" />
                  </template>

                </j-vxe-table>
              </a-tab-pane>
              <a-tab-pane tab="出库明细" :key="refKeys[1]" :forceRender="true">
                <j-vxe-table
                  keep-source
                  :ref="refKeys[1]"
                  :loading="crmShipmentGoodsOutboundTable.loading"
                  :columns="crmShipmentGoodsOutboundTable.columns"
                  :dataSource="crmShipmentGoodsOutboundTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="false"
                  :toolbar="false"
                />
              </a-tab-pane>
              <a-tab-pane tab="发货批次" :key="refKeys[3]" :forceRender="true">
                <j-vxe-table
                  keep-source
                  :ref="refKeys[3]"
                  :loading="crmShipmentGoodsOutBatchTempTable.loading"
                  :columns="crmShipmentGoodsOutBatchTempTable.columns"
                  :dataSource="crmShipmentGoodsOutBatchTempTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="true"
                >
                  <template v-slot:action="{ row }">
                    <a @click="handleClick(row)">选择批次</a>
<!--                    <a-divider type="vertical" />
                    <a @click="handleLook(row)">查看</a>-->
                    <OutBatchModal ref="outBatch" @ok="handleOutBatch" :materialCode="row.materialCode" :disabled="OutboundDisabled"  ></OutBatchModal>
                  </template>
                </j-vxe-table>
              </a-tab-pane>
            </a-tabs>
            <select-material-modal ref="selectModal" @orderOk="selMaterialOk" />
          </a-col>

<!--          <a-col :span="12" >-->
<!--            <a-form-model-item label="提单号" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="billLading">-->
<!--              <a-textarea v-model="model.billLading" placeholder="请输入提单号" rows="5" :disabled="formDisabled"></a-textarea>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->
<!--          <a-col :span="12" >-->
<!--            <a-form-model-item label="运输车号" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="vehicleNumber">-->
<!--              <a-textarea v-model="model.vehicleNumber" placeholder="请输入运输车号" rows="5" :disabled="formDisabled"></a-textarea>-->
<!--            </a-form-model-item>-->
<!--          </a-col>-->

          <a-col :span="8">
            <a-form-model-item
              label="当前车牌号："
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="plateNumber"
            >
              <plate-number-input
                v-model="model.plateNumber"
                @change="handleInput"
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="司机姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="driverName">
              <a-input v-model="model.driverName" placeholder="请输入司机姓名"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="联系电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="driverPhone" :rules="rules.driverPhone">
              <a-input v-model="model.driverPhone" placeholder="请输入联系电话"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="进厂目的" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purpose">
              <j-dict-select-tag type="list" v-model="model.purpose" dictCode="driver_purpose" placeholder="请选择进厂目的" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="提单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billLading">
              <a-input  v-model="model.billLading" placeholder="请输入提单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="notes">
              <a-input v-model="model.notes" placeholder="请输入备注"  ></a-input>
            </a-form-model-item>
          </a-col>


          <a-col :span="24" >
            <a-tabs  @change="handleChangeTabs">
              <a-tab-pane tab="附件" :key="refKeys[2]" :forceRender="true">
                <j-vxe-table
                  keep-source
                  :ref="refKeys[2]"
                  :loading="crmShipmentGoodsFilesTable.loading"
                  :columns="crmShipmentGoodsFilesTable.columns"
                  :dataSource="crmShipmentGoodsFilesTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="true"
                  :toolbar="true"
                >
                  <template v-slot:action="{ row }">
                    <a @click="handlePreviewReviewDesFiles(row)">预览</a>
                  </template>
                </j-vxe-table>
              </a-tab-pane>
            </a-tabs>
          </a-col>

        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->

  </a-spin>
</template>

<script>

import {getAction, postAction} from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import {
  getRefPromise,
  VALIDATE_FAILED,
  validateFormModelAndTables
} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import {FilePreview} from "@/utils/tslCommon";
import PlateNumberInput from '@views/srm/materialstore/modules/PlateNumberInput.vue'
import $table from 'vxe-table/packages/table/src/methods'
import TslErpCustomer from '@comp/tsl/TslErpCustomer.vue'
import OutBatchModal from '@views/crm/shipment/modules/OutBatchModal.vue'
import Outbound from '@views/trace/modules/outbound.vue'
import SelectMaterialModal from '@views/crm/shipment/modules/SelectMaterialModal.vue'

export default {
  name: 'CrmShipmentGoodsForm',
  mixins: [JVxeTableModelMixin],
  components: {
    SelectMaterialModal,
    OutBatchModal,
    TslErpCustomer,
    PlateNumberInput,
    JFormContainer,
  },
  data() {
    return {
      rules: {
        driverPhone: [
          {  message: '请输入联系电话', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入11位手机号码',
            trigger: 'blur'
          }
        ]
      },

      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      coRate:0,
      model:{
        priceType:1,
        plateNumber: '', // 确保 model 中有 plateNumber 字段
        province: '', // 确保 model 中有 province 字段
        plateBody: '', // 确保 model 中有 plateBody 字段
      },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        shipmentDate:[{ required:true,message:"请选择发货日期" }],
        flowFlag: [{ required: true, message: '请选择审批流程!' }],
      },
      OutboundDisabled:true,
      refKeys: [  'crmShipmentGoodsShipping','crmShipmentGoodsOutbound', 'crmShipmentGoodsFiles','crmShipmentGoodsOutBatch'],
      tableKeys:[ 'crmShipmentGoodsShipping','crmShipmentGoodsOutbound',  'crmShipmentGoodsFiles','crmShipmentGoodsOutBatch' ],
      activeKey: 'crmShipmentGoodsShipping',
      // 发货商品通知单-附件
      crmShipmentGoodsFilesTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '附件',
            key: 'files',
            type: JVXETypes.file,
            token:true,
            responseName:"message",
            placeholder: '请选择文件',
            defaultValue:'',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ]
      },
      // 发货商品通知单-出库明细
      crmShipmentGoodsOutboundTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            width:"200px",

          },
          {
            title: '物料编码',
            key: 'materialCode',
            width:"200px",
          },
          {
            title: '物料名称',
            key: 'materialName',
            width:"200px",
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            width:"200px",
          },
          {
            title: '主计量单位',
            key: 'unit',
            type: JVXETypes.select,
            options:[],
            dictCode:"ji_unit",
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '辅计量单位',
            key: 'secondaryUnit',
            type: JVXETypes.select,
            options:[],
            dictCode:"zl_unit",
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '生产日期',
            key: 'productionDate',
            width:"200px",
          },
          {
            title: '保质期(天)',
            key: 'shelfLife',
            width:"200px",
          },
          {
            title: '限用日期',
            key: 'restrictedDate',
            width:"200px",
          },
          {
            title: '供应商名称',
            key: 'supplierName',
            type: JVXETypes.input,
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '批次号',
            key: 'batchNumber',
            width:"200px",
          },
          {
            title: '物料批号',
            key: 'materialBatchNumber',
            width:"200px",
          },
          {
            title: '储位',
            key: 'storageLocation',
            width:"200px",
          },
          {
            title: '出库日期',
            key: 'outboundDate',
            width:"200px",
          },
          {
            title: '出库数量',
            key: 'auditQuantity',
            width:"200px",
          },
        ]
      },
      // 发货商品通知单-发货信息
      crmShipmentGoodsShippingTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '客户物料编码',
            key: 'customCode',
            width:"100px",
          },
          /*{
            title: '物料编码',
            type: JVXETypes.popup,
            popupCode:"shipmentSelectMaterial",
            orgFields:"custom_code,code,name,none_spec,me_unit,au_unit,quantity",
            destFields:"customCode,packageCode,packageName,noneSpec,meUnit,auUnit,inventoryQuantity",
            field:"custom_code,code,name,none_spec,me_unit,au_unit,quantity",
            key: 'packageCode',
            width:"100px",
          },*/
          {
            title: '物料编码',
            key: 'packageCode',
            width:"100px",
          },
          {
            title: '物料名称',
            key: 'packageName',
            width:"100px",
          },
          {
            title: '规格型号',
            key: 'noneSpec',
            width:"100px",
          },
          {
            title: '主计量单位',
            key: 'meUnit',
            type: JVXETypes.select,
            options:[],
            dictCode:"ji_unit",
            disabled:true,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '订单数量',
            key: 'mainQuantity',
            width:"100px",
          },
          {
            title: '已发数量',
            key: 'lssuedQuantity',
            width:"100px",
          },
          {
            title: '剩余未发',
            key: 'remainingUndelivered',
            width:"100px",
          },
          {
            title: '库存数量',
            key: 'inventoryQuantity',
            width:"100px",
          },
          {
            title: '仓库',
            key: 'warehouse',
            width:"100px",
          },
          {
            title: '本次发货数量',
            key: 'thisQuantity',
            type: JVXETypes.slot,
            defaultValue: 0,
            width:"100px",
            slotName: 'thisQuantity',
            statistics:['sum']
          },
          {
            title: '业务员',
            key: 'salesman_dictText',
            width:"100px",
          },
          {
            title: '辅计量单位',
            key: 'auUnit',
            type: JVXETypes.select,
            options:[],
            dictCode:"zl_unit",
            disabled:true,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '辅计量数量',
            key: 'auxiliaryQuantity',
            width:"100px",
            statistics:['sum']
          },
          {
            title: '单价',
            type:JVXETypes.slot,
            defaultValue: 0,
            key: 'unitPrice',
            slotName: 'unitPrice',
            width:"100px",
          },
          {
            title: '金额',
            key: 'amountMoney',
            width:"100px",
            statistics:['sum']
          },
          {
            title: '币种',
            key: 'currency',
            type: JVXETypes.select,
            options:[],
            dictCode:"currency",
            disabled:true,
            width:"100px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
        ]
      },
      //发货批次
      crmShipmentGoodsOutBatchTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编码',
            key: 'materialCode',
            popupCode:"outboundBatch",
   /*         orgFields:"material_code,material_name,customer_material_code,customer_name,specification_model," +
              "unit,batch_number,material_batch_number,storage_location",
            destFields:"materialCode,materialName,customerMaterialCode,customerName,specificationModel," +
              "unit,batchNumber,materialBatchNumber,storageLocation",
            field:"material_code,material_name,customer_material_code,customer_name,specification_model," +
              "unit,batch_number,material_batch_number,storage_location",*/
          /* param: {
             materialCode: "${this.crmShipmentGoodsOutboundTable.dataSource[0].materialCode}"   // 自动查询的字段条件
           },*/
            width:"200px",
          },
          {
            title: '物料名称',
            key: 'materialName',
            // width:"200px",
          },
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            width:"200px",
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            width:"200px",
          },
          {
            title: '主计量单位',
            key: 'unit',
            type: JVXETypes.select,
            options:[],
            dictCode:"ji_unit",
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '数量',
            type: JVXETypes.inputNumber,
            key: 'quantity',
            width:"200px",
            statistics:['sum']
          },
          {
            title: '批次号',
            type: JVXETypes.slot,
            key: 'batchNumber',
            width:"200px",
            slotName:'batchNumber'
          },
        ]
      },
      crmShipmentGoodsOutBatchTempTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物料编码',
            key: 'materialCode',
            popupCode:"outboundBatch",
            /*         orgFields:"material_code,material_name,customer_material_code,customer_name,specification_model," +
                       "unit,batch_number,material_batch_number,storage_location",
                     destFields:"materialCode,materialName,customerMaterialCode,customerName,specificationModel," +
                       "unit,batchNumber,materialBatchNumber,storageLocation",
                     field:"material_code,material_name,customer_material_code,customer_name,specification_model," +
                       "unit,batch_number,material_batch_number,storage_location",*/
            /* param: {
               materialCode: "${this.crmShipmentGoodsOutboundTable.dataSource[0].materialCode}"   // 自动查询的字段条件
             },*/
            width:"200px",
          },
          {
            title: '物料名称',
            key: 'materialName',
            // width:"200px",
          },
          {
            title: '客户物料编码',
            key: 'customerMaterialCode',
            width:"200px",
          },
          {
            title: '规格型号',
            key: 'specificationModel',
            width:"200px",
          },
          {
            title: '主计量单位',
            key: 'unit',
            type: JVXETypes.select,
            options:[],
            dictCode:"ji_unit",
            disabled:true,
            width:"200px",
            placeholder: '请输入${title}',
            defaultValue:'',
          },
          {
            title: '数量',
            key: 'quantity',
            width:"200px",
            statistics:['sum']
          },
          {
            title: '操作',
            type: JVXETypes.slot,
            width:"200px",
            slotName:'action'
          },
        ]
      },
      url: {
        add: "/shipment/crmShipmentGoods/add",
        edit: "/shipment/crmShipmentGoods/edit",
        queryById: "/shipment/crmShipmentGoods/queryById",
        queryOutBound: "/shipment/crmShipmentGoods/queryOutBound",
        crmShipmentGoodsFiles: {
          list: '/shipment/crmShipmentGoods/queryCrmShipmentGoodsFilesByMainId'
        },
        crmShipmentGoodsOutbound: {
          list: '/shipment/crmShipmentGoods/queryCrmShipmentGoodsOutboundByMainId'
        },
        crmShipmentGoodsShipping: {
          list: '/shipment/crmShipmentGoods/queryCrmShipmentGoodsShippingByMainId',
          queryByOrderId:'/shipment/crmShipmentGoods/queryCrmShipmentGoodsShippingByOrderId'
        },
        crmShipmentGoodsOutBatch:{
          list: '/shipment/crmShipmentGoods/queryOutboundOrderBatchItemByMainId',
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    } ,
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
    salesType:{type:String,
    required:true}
  },
  computed: {
    Outbound() {
      return Outbound
    },
    formDisabled(){
      return this.disabled
    },
  },
  created () {
    if (this.customFormData != null && this.customFormData.id) {
      this.model = this.customFormData
      this.editAfter() //现在子表内容需要
    }
    this.OutboundDisabled=this.disabled
    console.log('OutboundDisabled on created:', this.OutboundDisabled);
    this.model.salesType=this.salesType
    console.log("123",this.model)
  },
  methods: {
    selMaterialOk(rows) {
      console.log("rowsssss",rows)
      if (rows && rows.length > 0) {
        rows.forEach((item) => {
          let detail = {
            customCode:item.customCode,
            packageCode: item.code,
            packageName: item.name,
            noneSpec: item.noneSpec,
            meUnit: item.meUnit,
            inventoryQuantity: item.quantity,
            auUnit: item.auUnit,
            coRate: item.coRate
          }
          this.crmShipmentGoodsShippingTable.dataSource.push(detail)
        })
      }
    },
    addShipping() {
      console.log("1111111111111111")
      console.log('ref=', this.$refs.selectModal)   // 看是否为 undefined
      this.$nextTick(() => {
        this.$refs.selectModal.add()
      })
    },
    handleOutBatch(record){
      console.log("回调",record)
      record.forEach((item) => {
        item.wmsId=item.id
        item.quantity=item.thisQuantity
      })
      let flag =0
      this.crmShipmentGoodsOutBatchTable.dataSource =
        this.crmShipmentGoodsOutBatchTable.dataSource.filter(
          item => item.materialCode !== record[0].materialCode
        )
      this.crmShipmentGoodsOutBatchTable.dataSource.push(...record)
      console.log("结果",this.crmShipmentGoodsOutBatchTable.dataSource)
    },
    handleClick(row){
      console.log("111111111111",row)
      this.$nextTick(()=>{
        this.$refs.outBatch.add(row,this.crmShipmentGoodsOutBatchTable.dataSource.filter(item=>item.materialCode===row.materialCode))
      })
    },
/*    handleLook(row){
      console.log("111111111111",row)
      this.OutboundDisabled=true
      this.$nextTick(()=>{
      })
    },*/
    syncDataSource () {
      const $table = this.$refs[this.refKeys[3]]
      if (!$table) return
      console.log('ref 是否存在', this.$refs[this.refKeys[3]])
      console.log('getRecordset 返回', $table.getRecordset())
    },
    handleEditClosed(event) {
      let { $table, row, column } = event

      let field = column.property
      let cellValue = row[field]
      this.syncDataSource()
    },
    onDel() {
      const $table = this.$refs[this.refKeys[0]]
      const selectedRows = $table.getCheckboxRecords()
      if (!selectedRows.length) {
        this.$message.warning('请先勾选要删除的行')
        return
      }
      console.log("删除",selectedRows)
      $table.remove(selectedRows)
      this.crmShipmentGoodsShippingTable.dataSource =
        this.crmShipmentGoodsShippingTable.dataSource.filter(
          row => !selectedRows.includes(row)
        )
      this.syncDataSource()
    },
    onAddRow(){
      const newRow = {
        id: Date.now(),          // 行主键
        thisQuantity: 0,
        unitPrice: 0,
        // 其他字段默认值
      };
      console.log("实打实打算")
      this.$refs.crmShipmentGoodsShipping.insert(newRow);
      this.crmShipmentGoodsShippingTable.dataSource.push(newRow);
      this.syncDataSource()
    },
    handlePriceType(){
      this.crmShipmentGoodsShippingTable.dataSource.forEach(item=>{
        console.log("23131231231232",item)
        this.thisQuantityInput(item)
      })
    },
    //计算转换率
    noneSpecChange(record) {
      try {
          record.noneSpec = record.noneSpec.toUpperCase().trim()
          let tempSpec = record.noneSpec
          let k = tempSpec.indexOf('KG')
          let k1 = tempSpec.indexOf('G')

          let l1 = tempSpec.indexOf('ML')
          let l2 = tempSpec.indexOf('L')
          let c = tempSpec.indexOf('*')
          let t2 = tempSpec.substr(c + 1)
          console.log(c, t2, 'c-t2')
        console.log("sss",Number.parseFloat(t2))
           t2= Number.parseFloat(t2)>0?Number.parseFloat(t2):1
          let bt2 = c && c > -1 ? Number.parseFloat(t2) : 1
          if (k > 0) {
            let t1 = tempSpec.substr(0, k)
            let bt1 = Number.parseFloat(t1)

            this.coRate = ((bt1 * bt2) / 1000).toFixed(6)
          } else if (k1 > 0) {
            let t1 = tempSpec.substr(0, k1)
            let bt1 = Number.parseFloat(t1)

            this.coRate = ((bt1 * bt2) / 1000000).toFixed(6)
          } else if (l1 > 0) {
            let t1 = tempSpec.substr(0, l1)
            let bt1 = Number.parseFloat(t1)

            this.coRate = ((bt1 * bt2) / 1000000).toFixed(6)
          } else if (l2 > 0) {
            let t1 = tempSpec.substr(0, l2)
            let bt1 = Number.parseFloat(t1)
            this.coRate = ((bt1 * bt2) / 1000).toFixed(6)
          }
      } catch (e) {}
    },
    getCode() {
      postAction('/sys/fillRule/executeRuleByCode/shipment_goods_code', {}).then((res) => {
        this.model.shipmentCode = res.result
        this.$forceUpdate()
      })
    },
    handlePreviewReviewDesFiles(row) {
      if (row && row.files) {
        FilePreview(row.files)
      }
    },
    thisQuantityInput(row){
      const index = this.crmShipmentGoodsShippingTable.dataSource.findIndex(
        r => r.id === row.id   // 保证 id 唯一
      )
      let record =this.crmShipmentGoodsShippingTable.dataSource[index]
      if(record.thisQuantity>record.remainingUndelivered){
        record.thisQuantity=record.remainingUndelivered
      }
      console.log("hahaha",record.coRate)
      if(record.coRate===null ||record.coRate ===undefined){
        this.noneSpecChange(record)
        record.auxiliaryQuantity=this.coRate*record.thisQuantity
      }else {
        record.auxiliaryQuantity=record.coRate*record.thisQuantity
      }
      console.log("this.model.priceType:",this.model.priceType)
      if(this.model.priceType==1){
        console.log("---------111111------",this.model.priceType)
        //吨价
        record.amountMoney = Number(record.auxiliaryQuantity*record.unitPrice).toFixed(4)
        console.log("sas",this.model.priceType,record.thisQuantity,record.unitPrice,record.amountMoney)
      }else {
        console.log("---------222222222----",this.model.priceType)
        //件价
        record.amountMoney = Number(record.thisQuantity*record.unitPrice).toFixed(4)
        console.log("222",this.model.priceType,record.thisQuantity,record.unitPrice,record.amountMoney)
      }
      this.model.totalAmount =this.crmShipmentGoodsShippingTable.dataSource.reduce((sum, t) => sum + (Number(t.amountMoney) || 0), 0)
      console.log('拿到的实例', this.$refs[this.refKeys[0]])
      console.log('數組',this.crmShipmentGoodsShippingTable.dataSource)
      this.$refs[this.refKeys[0]].updateFooter()
      this.model.totalTonnage =Number(this.crmShipmentGoodsShippingTable.dataSource.reduce((sum, t) => sum + (t.auxiliaryQuantity || 0), 0)).toFixed(4)
      this.crmShipmentGoodsOutBatchTempTable.dataSource=[]
      this.crmShipmentGoodsShippingTable.dataSource.forEach(item=>{
        let temp={}
        temp.materialCode=item.packageCode
        temp.materialName=item.packageName
        temp.customerMaterialCode=item.customCode
        temp.specificationModel=item.noneSpec
        temp.unit=item.meUnit
        temp.quantity=item.thisQuantity
        this.crmShipmentGoodsOutBatchTempTable.dataSource.push(temp)
      })
      this.$forceUpdate()
    },
    addNew(){
      this.getCode()
      Vue.set(this.model, 'flowFlag', 1)
      if (typeof this.addBefore === 'function') this.addBefore()
    },
    add(record) {
      console.log("213132132",record)
      this.getCode()
      Vue.set(this.model, 'flowFlag', 1)
      Vue.set(this.model, 'documentType', record[0].documentType)
      Vue.set(this.model, 'salesType', record[0].salesType)
      Vue.set(this.model, 'contractBusinessType', record[0].contractBusinessType)
      Vue.set(this.model, 'customerId', record[0].customerId)
      Vue.set(this.model, 'customerName', record[0].customerName)
      Vue.set(this.model, 'address', record[0].address)
      Vue.set(this.model, 'moneyUnit', record[0].moneyUnit)
      if (typeof this.addBefore === 'function') this.addBefore()
      postAction(this.url.crmShipmentGoodsShipping.queryByOrderId,record).then((res)=>{
          if(res.success){
            this.crmShipmentGoodsShippingTable.dataSource=res.result
            this.model.totalTonnage = res.result.reduce((sum, t) => sum + (t.auxiliaryQuantity || 0), 0);
          }
        console.log('SSSSSSSSSSSS' ,this.crmShipmentGoodsShippingTable.dataSource)
        this.crmShipmentGoodsShippingTable.dataSource.forEach(item=>{
          let temp={}
          temp.materialCode=item.packageCode
          temp.materialName=item.packageName
          temp.customerMaterialCode=item.customCode
          temp.specificationModel=item.noneSpec
          temp.unit=item.meUnit
          this.crmShipmentGoodsOutBatchTempTable.dataSource.push(temp)
        })
      })
      console.log("sssssssssssssssssssssssssssssssssssssssssssssss",record[0])
      if(record[0].schedulingNumber!=undefined){
        getAction(this.url.queryOutBound,{id:record[0].schedulingNumber}).then((res)=>{
          this.crmShipmentGoodsOutboundTable.dataSource=res.result
        })
      }
      //this.edit(this.model)
    },

    /** 当点击了编辑（修改）按钮时调用此方法 */
    edit(record) {
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      // this.$refs.form.resetFields()
      console.log("record",record)
      this.model = Object.assign({}, record)
      if (typeof this.editAfter === 'function') this.editAfter(this.model)


    },

    addBefore(){
      this.crmShipmentGoodsFilesTable.dataSource=[]
      this.crmShipmentGoodsOutboundTable.dataSource=[]
      this.crmShipmentGoodsShippingTable.dataSource=[]
      this.crmShipmentGoodsOutboundTable.dataSource=[]
    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.crmShipmentGoodsFiles.list, params, this.crmShipmentGoodsFilesTable)
        //this.requestSubTableData(this.url.crmShipmentGoodsOutbound.list, params, this.crmShipmentGoodsOutboundTable)
        this.requestShipping(this.url.crmShipmentGoodsShipping.list, params, this.crmShipmentGoodsShippingTable)
      }
    },
    /** 查询某个tab的数据 */
    requestShipping(url, params, tab, success) {
      tab.loading = true
      getAction(url, params).then(res => {
        let { result } = res
        let dataSource = []
        if (result) {
          if (Array.isArray(result)) {
            dataSource = result
          } else if (Array.isArray(result.records)) {
            dataSource = result.records
          }
        }
        tab.dataSource = dataSource
        dataSource.forEach(item=>{
          let temp={}
          temp.materialCode=item.packageCode
          temp.materialName=item.packageName
          temp.customerMaterialCode=item.customCode
          temp.specificationModel=item.noneSpec
          temp.unit=item.meUnit
          temp.quantity=item.thisQuantity
          this.crmShipmentGoodsOutBatchTempTable.dataSource.push(temp)
        })
        // if(tab.dataSource){
        //   tab.dataSource = dataSource
        // }else{
        //   tab = dataSource
        // }
        if(dataSource[0].schedulingNumber!=undefined) {
          getAction(this.url.queryOutBound, { id: dataSource[0].schedulingNumber }).then((res) => {
            this.crmShipmentGoodsOutboundTable.dataSource = res.result
          })
        }
        getAction(this.url.crmShipmentGoodsOutBatch.list,params).then((res)=>{
           if(res.success){
             this.crmShipmentGoodsOutBatchTable.dataSource=res.result
        }})
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        tab.loading = false
      })
    },
    //校验所有一对一子表表单
    validateSubForm(allValues){
      return new Promise((resolve,reject)=>{
        Promise.all([
        ]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      console.log("1231232131",allValues)
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        crmShipmentGoodsFilesList: allValues.tablesValue[2].tableData,
        crmShipmentGoodsOutboundList: allValues.tablesValue[1].tableData,
        crmShipmentGoodsShippingList: allValues.tablesValue[0].tableData,
        outboundOrderBatchItemList: this.crmShipmentGoodsOutBatchTable.dataSource,
      }
    },
    validateError(msg){
      this.$message.error(msg)
    },
    handleInput(val) {
      console.log('车牌号变更11:', val)
      this.model.plateNumber = val.plateNumber; // 确保值正确更新
      this.model.province = val.province;
      this.model.plateBody = val.plateBody;
    },
    handleOk() {
      console.log("123",this.model)
      this.crmShipmentGoodsShippingTable.dataSource.forEach(item=>{
        if(item.thisQuantity===null||item.thisQuantity===undefined||item.thisQuantity<=0){
          return this.$message.warning("发货信息的各个物料的本次发货数量需要大于零")
        }
      })
      if (this.crmShipmentGoodsOutBatchTable.dataSource.length > 0) {
        console.log("发货信息表",this.crmShipmentGoodsShippingTable.dataSource)
        console.log("发货批次表",this.crmShipmentGoodsOutBatchTable.dataSource)
        const validOutList = this.crmShipmentGoodsOutBatchTable.dataSource
          .filter(item => Number(item.quantity) !== 0);
        const outMap  = this.sumByKey(validOutList, 'materialCode', 'quantity');
        const shipMap = this.sumByKey(this.crmShipmentGoodsShippingTable.dataSource,
          'packageCode', 'thisQuantity');
        const errors = [];
        outMap.forEach((q1, code) => {
          const q2 = shipMap.get(code) || 0;
          console.log('aaaaaaaaaaaaaaaaaaaa', code, q1, q2);
          if (q1 !== q2) {
            errors.push({ code, quantitySum: q1, thisQuantitySum: q2 });
          }
        });
        if (errors.length) {
          const codes = errors.map(e => e.code).join(',')
          this.$message.error(`以下编码物料的发货批次数量与发货信息的本次发货数量不一致：${codes}`)
          console.error('不一致的编码：', errors)
          return
        } else {
          console.log('全部相等 ✔')
        }
      }
      /** 触发表单验证 */
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormModelAndTables(this.$refs.form,this.model, tables)
      }).then(allValues => {
        /** 一次性验证一对一的所有子表 */
        return this.validateSubForm(allValues)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }
        let formData = this.classifyIntoFormData(allValues)
        // 发起请求
        return this.request(formData)
      }).catch(e => {
        if (e.error === VALIDATE_FAILED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
    },
    sumByKey (arr, keyField, valField) {
      const map = new Map()
      arr.forEach(r => {
        const k = r[keyField]
        const v = Number(r[valField]) || 0
        map.set(k, (map.get(k) || 0) + v)
      })
      return map
    },
  }
}

</script>

<style scoped>
</style>